import React, { Component } from 'react';

import Loading from '@/components/loading';
import Modal from '@/components/modal';
import Toast from '@/components/toast';
import classNames from 'classnames';
import api from '@/utils/fetch';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tel: '',
      code: '',
      address: '',
      cats: [
        {
          id: 0,
          name: '蔬菜',
          isActive: false
        },
        {
          id: 1,
          name: '水果',
          isActive: false
        },
        {
          id: 2,
          name: '其他',
          isActive: false
        }
      ],
      vendors: [
        {
          id: 0,
          name: '美团外卖',
          isActive: false
        },
        {
          id: 1,
          name: '京东到家',
          isActive: false
        },
        {
          id: 2,
          name: '饿百',
          isActive: false
        }
      ],
      wait: 0
    };
    this.timer = null;
  }
  changeCat = id => {
    this.setState({
      cats: this.state.cats.map(item => {
        if (item.id === id) {
          return {
            ...item,
            isActive: !item.isActive
          };
        } else {
          return {...item};
        }
      })
    });
  }
  changeVendor = id => {
    this.setState({
      vendors: this.state.vendors.map(item => {
        if (item.id === id) {
          return {
            ...item,
            isActive: !item.isActive
          };
        } else {
          return {...item};
        }
      })
    });
  }
  // 获取短信验证码
  getCode = () => {
    if (this.state.wait !== 0) return false;
    let tel = this.refs.tel.value.trim();
    if (!/\d{11}/g.test(tel)) {
      Toast.show('请输入正确手机号');
      return false;
    }
    Modal.show({
      title: '验证码',
      modalType: 'code',
      confirm: async (id, code) => {
        console.log(id, code);
        await this.sendCode(id, code, tel);
      }
    })
  }
  // 倒计时
  countDown = () => {
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      if (this.state.wait === 0) {
        clearInterval(this.timer);
      } else {
        this.setState({
          wait: this.state.wait - 1
        });
      }
    }, 1000)
  }
  // 发送验证码
  sendCode = async (id, code, tel) => {
    try {
      Loading.show();
      let form = new FormData();
      form.append('captchaID', id)
      form.append('captchaValue', code)
      form.append('authID', tel)
      await api('/v2/auth2/SendVerifyCode', {
        method: 'POST',
        body: form
      });
      Toast.show('获取成功，请注意查收');
      await this.setState({wait: 59});
      this.countDown();
    } catch (e) {
      console.log(e);
      Modal.show({
        title: '错误',
        showCancel: false,
        message: e,
        center: true
      });
    } finally {
      Loading.hide();
    }
  }
  // 申请入驻
  Tenants = async () => {
    try {
      Loading.show();
      let tel = this.refs.tel.value.trim();
      let address = this.refs.address.value.trim();
      let {vendors, cats} = this.state;
      let msgContent = `
        门店电话: ${tel},
        门店地址: ${address},
        门店主营品类: ${cats.filter(item => item.isActive).map(item => item.name).join(',')},
        已入驻平台: ${vendors.filter(item => item.isActive).map(item => item.name).join(',')}
      `;
      console.log(msgContent);
      let form = new FormData();
      form.append('mobile', tel);
      form.append('verifyCode', this.refs.code.value.trim());
      form.append('msgType', 'openStoreRequest');
      form.append('msgContent', msgContent );
      let res = await api('/v2/cms/SendMsg2Somebody', {
        method: 'POST',
        body: form
      });
      console.log(res);
      Modal.show({
        title: '申请成功',
        message: '我们会尽快与您取得联系！',
        center: true,
        showCancel: false,
        confirmText: '好的'
      })
    } catch (e) {
      console.log(e);
      Modal.show({
        title: '错误',
        showCancel: false,
        message: e,
        center: true
      });
    } finally {
      Loading.hide();
    }
  }
  render() {
    const {cats, vendors, wait} = this.state;
    return (
      <div className="store-in">
        <div className="header"></div>
        {/* 门店电话 */}
        <div className="cell">
          <label className="cell-title" htmlFor="tel">
            <span>门店电话</span>
            <span>※</span>
          </label>
          <input id="tel" ref="tel" className="input-normal" type="tel" placeholder="门店电话"/>
          <div className={classNames({'button-small': true, 'button-disable': wait !== 0})} onClick={this.getCode}>
            {
              wait !== 0 ? `获取短信验证(${wait})` : '获取短信验证'
            }
          </div>
        </div>
        {/* 短信验证码 */}
        <div className="cell">
          <label className="cell-title" htmlFor="code">
            <span>短信验证</span>
            <span>※</span>
          </label>
          <input id="code" ref="code" className="input-normal" type="number" placeholder="短信验证码"/>
        </div>
        {/* 门店地址 */}
        <div className="cell">
          <label className="cell-title" htmlFor="address">
            <span>门店地址</span>
            <span>※</span>
          </label>
          <input id="address" ref="address" className="input-normal" type="text" placeholder="门店详细地址"/>
        </div>
        {/* 门店主营品类 */}
        <div className="cell2">
          <div className="cell-title">
            <span>门店主营品类</span>
            <span>（此处可多选）</span>
          </div>
          <div className="checkbox">
          {
            cats.map(item => (
              <div className={classNames({'check-item': true, 'check-on': item.isActive})} key={item.id} onClick={this.changeCat.bind(this, item.id)}>{item.name}</div>
            ))
          }
          </div>
        </div>
        {/* 入驻平台 */}
        <div className="cell2">
          <div className="cell-title">
            <span>已入驻平台</span>
            <span>（此处可多选）</span>
          </div>
          <div className="checkbox">
          {
            vendors.map(item => (
              <div className={classNames({'check-item': true, 'check-on': item.isActive})} key={item.id} onClick={this.changeVendor.bind(this, item.id)}>{item.name}</div>
            ))
          }
          </div>
        </div>
        <div className="button-big" onClick={this.Tenants}>立即申请入驻</div>
        <a className="protocal" href="http://www.jxc4.com/protocal">阅读协议</a>
      </div>
    );
  }
}
 
export default App;